package com.simple.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.simple.entity.CodeResult;
import com.simple.entity.StatusCode;
import com.simple.entity.SysRole;
import com.simple.entity.vo.SysRoleVo;
import com.simple.service.SysRoleService;
import com.simple.utils.JsonUtils;
import com.simple.utils.SysConfig;
import com.simple.utils.TableUtils;

/**
 * 角色管理
 * 
 */
@Controller
@RequestMapping("/user")
public class SysRoleController {
	
	private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

	@Autowired
	SysRoleService sysRoleService;
	
	@RequestMapping("/sysRole.html")
	public String sysRole() {
		return "sysRole";
	}

	//表格数据
	@RequiresPermissions("sysRole:view")
	@RequestMapping(value="/sysRole/list.html")
	@ResponseBody
	public JSONObject tableRole(){
		List<SysRoleVo> list=sysRoleService.findAllRoles();
		logger.debug("返回值："+TableUtils.tableResult(list));
		return TableUtils.tableResult(list);
	}
	
	//编辑
	@RequiresPermissions(value={"sysRole:edit","sysRole:view"},logical = Logical.OR)
	@RequestMapping("/sysRole/edit.html")
	public String editMenuIframe(HttpServletRequest request,Model model) {
		String id=request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			SysRole sysRole=sysRoleService.findByRoleId(Integer.valueOf(id));
			String menuId=sysRole.getMenuId();
			model.addAttribute("menuId", menuId);
			model.addAttribute("sysRole", sysRole);
		}
		return "sysRoleEdit";
	}
	//添加
	@RequiresPermissions("sysRole:edit")
	@RequestMapping("/sysRole/add.html")
	@ResponseBody
	public CodeResult addMenu(SysRole sysRole,Model model) {
		logger.info(sysRole.toString());
		String menuId=sysRole.getMenuId();
		sysRole.setMenuId(JsonUtils.jsonToString(menuId));
		logger.info("-------"+JsonUtils.jsonToString(menuId));
		sysRoleService.saveAndFlush(sysRole);
		return CodeResult.success(StatusCode.ADD_SUCCESS);
	}
	//删除
	@RequiresPermissions("sysRole:edit")
	@RequestMapping("/sysRole/delete/{id}.html")
	@ResponseBody
	public CodeResult deleteMenu(@RequestParam("id")Integer id,Model model) {
		sysRoleService.deleteById(id);
		return CodeResult.success(StatusCode.DELETE_SUCCESS);
	}
}
